<template>
    <div class="point-wrapper">
        <cardBox class="colum" title="测点类型" >
            <template #right>
                <el-button type="primary" size="mini" icon="el-icon-circle-plus-outline" @click="handleAddPointType()" v-if="showRoleAdd">新增测点类型</el-button>
            </template>
              <div class="inupt-style">
                <el-input v-model="searchName" placeholder="关键字查询" size="small" style="width:100%"  @keyup.enter.native="getTypeDataList"/>
              </div>
                <el-table  height="calc(100vh - 320px)" :data="tableData"
                highlight-current-row border style="margin-top:10px;" @row-click="handleRowClick">
              <el-table-column align="center" label="编号" type="index" width="50" />
              <el-table-column prop="instrumentModelName" align="center" label="仪器型号"></el-table-column>
              <el-table-column prop="instR_Name" align="center" label="测点分类"></el-table-column>
              <el-table-column prop="factoryName" align="center" label="厂家"></el-table-column> 
              <el-table-column align="center" label="操作"  width="160">
                <template slot-scope="scope">
                  <el-tooltip class="item" effect="dark" content="编辑测点类型" placement="top-start">
                    <el-button class="typesBtn" type="primary" size="small" icon="el-icon-edit" @click="handleAddPointType(scope.row)" v-if="showRoleEdit"></el-button>
                  </el-tooltip>
                  <el-tooltip class="item" effect="dark" content="分量设置" placement="top-start">
                    <el-button class="typesBtn" type="primary" size="small" icon="el-icon-setting" @click="handleCompSet(scope.row)" v-if="showRoleEdit"></el-button>
                  </el-tooltip>
                  <el-tooltip class="item" effect="dark" content="删除测点类型" placement="top-start">
                    <el-button class="typesBtn" type="danger" size="small" icon="el-icon-delete" @click="handleDelPoint(scope.row)" v-if="showRoleDel"></el-button>
                  </el-tooltip>
                  <el-tooltip class="item" effect="dark" content="导出数据" placement="top-start">
                    <el-button class="typesBtn" type="success" size="small" icon="el-icon-upload2" @click="handleExportPoint(scope.row)" ></el-button>
                  </el-tooltip>
                </template>
              </el-table-column>
            </el-table>
        </cardBox>
        <cardBox class="colum" title="测点列表">
            <template #right>
                <el-button type="primary" size="mini" icon="el-icon-circle-plus-outline" @click="handleAddPointClick()" :disabled="pointInstR_ID == ''" v-if="showRoleAdd">新增测点</el-button>
            </template>

             <div class="inupt-style">
                <el-input v-model="searchNamePoint" placeholder="关键字查询" size="small" style="width:100%"  @keyup.enter.native="getPointList"/>
              </div>

            <el-table :data="powerpointList" height="calc(100vh - 320px)" border row-key="id"
               default-expand-all
              :tree-props="{children: 'children', hasChildren: 'hasChildren'}"> 
              <el-table-column align="center" label="编号" type="index" width="50"/>
              <el-table-column prop="pointName" label="测点名称" align="center"></el-table-column>
              <el-table-column  prop="workStatus" label="状态" align="center"/>
              <el-table-column  label="操作" width="160" align="center">
                  <template slot-scope="scope">
                    <el-tooltip class="item" effect="dark" content="增加子级" placement="top-start">
                      <el-button class="typesBtn" type="primary" size="small" icon="el-icon-plus" @click="handleAddChildren(scope.row,false)" 
                       v-if="showRoleAdd && productTypeID == 7 && !scope.row.codE_ID"
                      ></el-button>
                    </el-tooltip>
                    <el-tooltip class="item" effect="dark" content="编辑测点" placement="top-start">
                      <el-button class="typesBtn" type="primary" size="small" icon="el-icon-edit" @click="handleAddPointClick(scope.row)" v-if="!scope.row.codE_ID && showRoleEdit"></el-button>
                    </el-tooltip>
                    <el-tooltip class="item" effect="dark" content="编辑测点" placement="top-start">
                      <el-button class="typesBtn" type="primary" size="small" icon="el-icon-edit" @click="handleAddChildren(scope.row,true)" 
                      v-if="showRoleEdit && scope.row.codE_ID"
                     ></el-button>
                    </el-tooltip>
                    <el-tooltip class="item" effect="dark" content="删除测点" placement="top-start">
                      <el-button class="typesBtn" type="danger" size="small" icon="el-icon-delete" @click="handleDelPointClick(scope.row,'del')" v-if="!scope.row.codE_ID && showRoleDel"></el-button>
                    </el-tooltip>
                    <el-tooltip class="item" effect="dark" content="删除测点" placement="top-start">
                      <el-button class="typesBtn" type="danger" size="small" icon="el-icon-delete" @click="handleDelChildren(scope.row)"
                      v-if="showRoleDel && scope.row.codE_ID"></el-button>
                    </el-tooltip>
                    <el-tooltip class="item" effect="dark" content="导出数据" placement="top-start">
                    <el-button class="typesBtn" type="success" size="small" icon="el-icon-upload2" @click="handleExportPointClick(scope.row)" v-if="!scope.row.codE_ID"></el-button>
                  </el-tooltip>
                  </template>
                </el-table-column>
            </el-table>
        </cardBox>



        <el-dialog title="测点类型配置" :visible.sync="pointTypeDialog" width="80%" v-dialogDrag :before-close="handleClosePointTypeDialog">
      <div class="dialog-company">
        <div class="company-left">
          <el-form ref="pointTypeForm" :model="pointTypeForm" label-width="100px">
            <el-form-item  v-if="pointTypeForm.instrumentModelName" label="当前仪器">
              <span class="blueText" style="font-weight: bold;">{{pointTypeForm.instrumentModelName}}</span>
            </el-form-item>
            <el-form-item label="厂家选择">
              <el-select size="small" v-model="factoryId" placeholder="请选择所属厂家" @change="handleChagneFacturers">
                <el-option
                  v-for="item in manufacturersOptions"
                  :key="item.id" 
                  :label="item.factoryName"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="选择仪器">
                <treeMenu :treeData="instrumentList" name="name"  @menuLeftClick="handleMenuClick" ref="treeMenu" class="treeMenu" expandALL/>
            </el-form-item>
            <el-form-item label="类型名称">
              <el-input size="small" class="searchIpt" v-model="pointTypeForm.instR_Name" placeholder="请输入"/>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" size="small" icon="el-icon-circle-check" @click="handleSavePointSet">保存</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div class="company-right">
            <div class="company-list-title">
              仪器分量
            </div>
            <instrumentTable :instrumentModelID="instrumentModelID" height="calc(100vh - 600px)"/>
            <div class="company-list-title" style="margin-top: 20px;">
              仪器参数
            </div>
            <div class="list-box1">
              <el-table  :data="paramList" height="calc(100vh - 700px)">
                <el-table-column align="center" label="参数" prop="param"/>
                <el-table-column align="center" label="参数名称" prop="parameterName"/>
                <el-table-column align="center" label="单位" prop="unit"/>
              </el-table>
            </div>
        </div>
      </div>
      </el-dialog>

      <el-dialog  title="分量设置" :visible.sync="compSetDialog" v-dialogDrag width="80%" :before-close="handleCloseCompSetDialog">
        <instrumentTable :instrumentModelID="instrumentModelID" height="calc(100vh - 300px)"  :instR_ID="instR_ID" isSet/>
      </el-dialog>

      <el-dialog  title="测点配置" :visible.sync="pointFormDialog" width="450px" v-dialogDrag :before-close="handleCanCelPoint">
        <el-form ref="pptForm" :model="pointForm" label-width="100px">
          <el-form-item label="测点名称">
            <el-input class="searchIpt" v-model="pointForm.pointName" placeholder="请输入"/>
          </el-form-item>
        </el-form>
        <div class="btnGroup">
          <el-button  size="small" icon="el-icon-circle-close" @click="handleCanCelPoint">取消</el-button>
           <el-button type="primary" size="small" icon="el-icon-circle-check" @click="handleSavePoint">保存</el-button>
        </div>
      </el-dialog>

      <el-dialog  title="新增/编辑子级测点" :visible.sync="pointDialogChildrenVisible" width="450px" v-dialogDrag>
        <el-form ref="pptForm" :model="pointChildrenForm" label-width="100px">
          <el-form-item label="测点名称">
            <el-input class="searchIpt" v-model="pointChildrenForm.burialDepth" placeholder="请输入"/>
          </el-form-item>
          <el-form-item>
            
          </el-form-item>
        </el-form>
        <div class="btnGroup">
          <el-button  size="small" icon="el-icon-circle-close" @click="handleCanCelPointChildren">取消</el-button>
           <el-button type="primary" size="small" icon="el-icon-circle-check" @click="handleSavePointChildren">保存</el-button>
        </div>
    </el-dialog>


    </div>
</template>
<script>

import {GetPowerPointType,GetAllFactory,GetInstrumentObj,GetParameterByModeId,EditPowerPointType,AddPowerPointType,DelPowerPointType,QueryPointByName,AddPowerPoints,EditPowerPoints,DelPowerPoints,PowerPointHeartWallAdd,PowerPointHeartWallEdit,PowerPointHeartWallDel} from '@/api/https'
import cardBox from "@/components/base/cardBox.vue";
import treeMenu from '@/components/base/treeMenu.vue'
import instrumentTable from '@/components/page/setting/InstrumentTable.vue'
import {baseUrl} from '@/api/baseUrl'
export default ({
    components:{cardBox,treeMenu,instrumentTable},
    props:{
        stationId:{
            type:[String,Number],
            default:''
        },
        showRoleAdd:{
          type:Number,
          default:0
        },
        showRoleEdit:{
          type:Number,
          default:0
        },
        showRoleDel:{
          type:Number,
          default:0
        }
    },
    data() {
        return{
            tableData:[],
            searchName:'',
            editPointType:false,
            pointTypeForm:{},
            pointTypeDialog:false,
            manufacturersOptions:[],
            factoryId:'',
            instrumentList:[],
            instrumentModelID:'',
            productTypeID:'',
            paramList:[],
            compSetDialog:false,
            compSetList:[],
            instR_ID:'',
            powerpointList:[],
            pointInstR_ID:'',
            pointProductTypeID:'',
            searchNamePoint:'',
            editPointData:false,
            pointForm:{},
            pointFormDialog:false,
            pointChildrenForm:{},
            pointDialogChildrenVisible:false,
            editChildren:false
        }   
    },
    mounted(){
        this.getTypeDataList()
    },
    methods:{
        getTypeDataList(){
            GetPowerPointType(this.searchName,this.stationId,1,100).then(res=>{
                if (res.isSuccess) {            
                    this.tableData = res.data.data || []
                }
          });
        },
        getFactory() {
            GetAllFactory().then(res=>{
                if (res.isSuccess && res.data && res.data.length > 0) {
                    this.manufacturersOptions = res.data || []
                    this.factoryId = res.data[0].id
                    this.getInstrument()
                }else{
                    this.manufacturersOptions = []
                    this.factoryId = ''
                }
            });
        },
        getInstrument() {
            GetInstrumentObj({
                FactoryID:this.factoryId
            }).then(res=>{
                if (res.isSuccess && res.data && res.data.length > 0) {
                    this.instrumentList = res.data;
                }else{
                    this.instrumentList = []
                    this.$message.error(res.errorMessage)
                }
            });
        },
        handleChagneFacturers(){
            this.getInstrument()
        },
        handleMenuClick(data){
           if(data.productTypeID){
              this.instrumentModelID = data.id,
              this.productTypeID = data.productTypeID
              this.getApparatus()
           }else{
              this.instrumentModelID = ''
              this.paramList = []
           }
        },
        getApparatus() {
            GetParameterByModeId(this.instrumentModelID).then(res=>{
                if (res.isSuccess) {
                    this.paramList = res.data || []
                }
            });
        },
        handleAddPointType(data) {
            if(this.manufacturersOptions.length <= 0){
                this.getFactory()
            }
            if (data) {
                this.$nextTick(()=>{
                  this.$refs.treeMenu.$refs.tree.setCurrentKey(data.instrumentModelID);
                  this.instrumentModelID = data.instrumentModelID,
                  this.productTypeID = data.productTypeID
                  this.getApparatus()
                })
                this.editPointType = true
                this.pointTypeForm = {
                    instR_ID: data.instR_ID,
                    instrumentModelID: data.instrumentModelID,
                    instR_Name: data.instR_Name,
                    station_ID: data.station_ID,
                    instrumentModelName: data.instrumentModelName
                }
            } else {
                this.editPointType = false
                this.pointTypeForm = {
                    instR_ID:0,
                    station_ID:this.stationId,
                    instR_Name:'',
                    instrumentModelID:this.instrumentModelID,
                    productTypeID:this.productTypeID,
                }
            }
            this.pointTypeDialog = true
        },
        handleDelPoint(data){
          this.$confirm(`删除分类将会删除此分类下所有测点数据,建议先导出数据！确认删除名为[${data.instR_Name}]的测点类型？`,'提示',{
            type:'warning'
          }).then(() => {
                DelPowerPointType(data.instR_ID).then(res=>{
                  if(res.isSuccess){
                      this.$message.success("删除成功");
                      this.getTypeDataList();
                  }else{
                      this.$message.error(res.errorMessage)
                  }
                })
          }).catch(() => {});  
        },
        handleExportPoint(rowData){
           window.location.href = `${baseUrl.httpUrl}/PowerPointType/outputData?INSTR_ID=${rowData.instR_ID}`
        },
        handleClosePointTypeDialog(){
          this.instrumentModelID = ''
          this.productTypeID = ''
          this.pointTypeForm = {}
          this.editPointType = false
          this.pointTypeDialog = false;
          this.paramList = []
          this.$refs.treeMenu.$refs.tree.setCurrentKey(null);
        },
        handleCloseCompSetDialog(){
          this.instR_ID = ''
          this.instrumentModelID = ''
          this.compSetDialog = false
        },
        handleSavePointSet() {
          const _data = {
            ...this.pointTypeForm,
            instrumentModelID:this.instrumentModelID,
            productTypeID:this.productTypeID,
          }
          if (this.editPointType) {
            EditPowerPointType(_data).then(res=>{
              if(res.isSuccess){ 
                this.$message.success("编辑成功");
                this.pointTypeDialog = false;
                this.getTypeDataList()
              }else{
                this.$message.error(res.errorMessage);
              }
            })
          } else {
            AddPowerPointType(_data).then(res=>{
              if(res.isSuccess){
                this.$message.success("新增成功");
                this.pointTypeDialog = false;
                this.getTypeDataList();
              }else{
                this.$message.error(res.errorMessage);
              }
            })
          }
        },
        handleCompSet(data){
          this.instrumentModelID = data.instrumentModelID
          this.instR_ID = data.instR_ID
          this.compSetDialog = true
        },
        handleRowClick(rowData) {
          this.pointInstR_ID = rowData.instR_ID;
          this.pointProductTypeID = rowData.productTypeID
          this.getPointList();
        },
        getPointList() {
          QueryPointByName({
            INSTR_ID:this.pointInstR_ID,
            name:this.searchNamePoint,
            ProductTypeID:this.pointProductTypeID
          }).then(res=>{
            if (res.isSuccess) {
              this.powerpointList = res.data || [];
              if(this.powerpointList.length > 0){
                this.powerpointList.forEach(item => {
                  const matched = this.treesData.find(({codE_ID}) => codE_ID === item.id);
                  if (matched) {
                    Object.assign(item, { workStatus: '已使用' });
                  } else {
                    Object.assign(item, { workStatus: '未使用' });
                  }
                })
              }
            }
          });
        },
        handleAddPointClick(rowData){
          if (rowData) {
            this.editPointData = true
            this.pointForm = { ...rowData}
          }else{
            this.editPointData = false
            this.pointForm = {
              id: this.stationId,
              instR_ID: this.pointInstR_ID,
              pointName: "",
              workStatus: "",
              collectionTypes: "",
              location: "",
              startingDate: "",
              horizontalPile: "",
              verticalPile: "",
              elevation: "",
              connectionPA: 0,
              isConnection: 0,
              remark: "",
              treeid: 0,
              upTreeID: 0
            }
          }
          this.pointFormDialog = true;   
        },
        handleDelPointClick(data){
           this.$confirm(`删除分类将会删除此测点数据，建议先导出数据！确认删除名为[${data.pointName}]的测点类型？`,'提示',{
            type:'warning'
           }).then(() => {
              DelPowerPoints(data.id).then(res=>{
                if(res.isSuccess){
                  this.$message.success("删除成功");
                  this.getPointList();
                }
              })
            }).catch(() => {});
        },
        handleDelChildren(data){
          this.$confirm(`删除分类将会删除此测点数据，建议先导出数据！确认删除名为[${data.pointName}]的测点类型？`,'提示',{
            type:'warning'
           }).then(() => {
            PowerPointHeartWallDel({
              ID:data.id
            }).then(res=>{
                if(res.isSuccess){
                  this.$message.success("删除成功");
                  this.getPointList();
                }
              })
          }).catch(() => {}); 
        },
        handleExportPointClick(data){
          window.location.href = `${baseUrl.httpUrl}/PowerPoint/outputData?INSTR_ID=${data.instR_ID}&ID=${data.id}`
        },
        handleCanCelPoint(){
          this.pointFormDialog = false
          this.pointForm = {}
          this.editPointData = false
        },
        handleSavePoint() {
          if (this.editPointData) {
             EditPowerPoints(this.pointForm).then(res=>{
              if(res.isSuccess){
                this.$message.success("编辑成功");
                this.handleCanCelPoint()
                this.getPointList();
              }
            })
          } else {
            AddPowerPoints(this.pointForm).then(res=>{
              if(res.isSuccess){
                this.$message.success("新增成功");
                this.handleCanCelPoint()
                this.getPointList();
              }
            })
          }
        },
        handleAddChildren(data,isEdit){
          this.editChildren = isEdit
          this.pointChildrenForm = {
            workStatus:data.workStatus || '正常在测',
            id:data.id || 0,
            burialDepth:data.pointName || '',
            codE_ID:isEdit ? data.codE_ID || '' : data.id || ''
          }

          this.pointDialogChildrenVisible = true
        },
        handleCanCelPointChildren(){
          this.pointDialogChildrenVisible = false
          this.pointChildrenForm = {}
          this.editChildren = false
        },
        handleSavePointChildren(){
          if(this.editChildren){
            PowerPointHeartWallEdit(this.pointChildrenForm).then(res=>{
              if(res.isSuccess){
                this.handleCanCelPointChildren()
                this.getPointList();
              }
            })
          }else{
            PowerPointHeartWallAdd(this.pointChildrenForm).then(res=>{
              if(res.isSuccess){
                this.handleCanCelPointChildren()
                this.getPointList();
              }
            })
          }
        }
    }
})
</script>
<style scoped lang="scss">
.point-wrapper{
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 10px; 
    .colum{
        height: calc(100vh - 180px) ;
        margin-top:10px;
    }
}
.inupt-style{
    width:90%;
    margin:10px auto;
}
.typesBtn {
  padding: 5px;
  margin: 0 4px !important;
  border:none !important;
}
.dialog-company{
    display: flex;
    flex-direction: row;
    justify-content: start;
    .company-left{
        width:400px;
        .treeMenu{
            height: calc(100vh - 500px);
            overflow: auto;
        }
    }
    .company-right{
        flex:1;
        margin-left: 20px;
        overflow: hidden;
    }
}
.company-list-title{
  font-weight: bold;
  line-height: 35px;
}
.list-box1{
  width: 100%;
  overflow: auto;
}
::v-deep .el-form-item{
  margin-bottom: 6px !important;
}
</style>
